/*
 * 此文件时间相关的函数
 * */

// 秒数转时分秒
export const formatSeconds = (result) => {
  let h =
    Math.floor(result / 3600) < 10
      ? "0" + Math.floor(result / 3600)
      : Math.floor(result / 3600);
  let m =
    Math.floor((result / 60) % 60) < 10
      ? "0" + Math.floor((result / 60) % 60)
      : Math.floor((result / 60) % 60);
  let s =
    Math.floor(result % 60) < 10
      ? "0" + Math.floor(result % 60)
      : Math.floor(result % 60);
  return (result = h + ":" + m + ":" + s);
};
// 格式化日期  "yyyy-MM-dd" "yyyy-MM-dd HH:mm:ss"
export const formatDate = (time, fmt = "yyyy-MM-dd") => {
  const date = new Date(time);
  let o = {
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    S: date.getMilliseconds(), //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (let k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  return fmt;
};

export const calculateTimeDifference = (
  start = Date.now(),
  end = Date.now(),
  unit = "s"
) => {
  // 将时间戳转换为日期对象
  const startDate = new Date(start);
  const endDate = new Date(end);

  // 计算时间差，单位是秒
  let diff = (endDate.getTime() - startDate.getTime()) / 1000;

  // 根据传入的时间单位进行转换
  if (unit === "m") {
    diff /= 60;
  } else if (unit === "h") {
    diff /= 3600;
  }

  return diff;
};
